package com.zzy.test;


import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class U2 {
    private static LdapContext ctx = null;

    private static String root = "OU=软件研发部,DC=zxf,DC=com";


    public static void LDAP_connect(ADConfig adConfig ) {
        String url = new String("ldaps://" +adConfig.getAD_SERVER()  +":" + adConfig.getAD_SERVER_PORT());
        //Hashtable env = new Hashtable();
        //env.put(Context.SECURITY_AUTHENTICATION, "simple");
        //env.put(Context.SECURITY_PRINCIPAL, adConfig.getAD_ACCOUNT() + "@" + adConfig.getDN());
        //env.put(Context.SECURITY_CREDENTIALS, adConfig.getAD_PASSWORD());
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        //env.put(Context.REFERRAL, "follow");
        //env.put("com.sun.jndi.ldap.read.timeout", "6000");
        //env.put(Context.PROVIDER_URL, url);
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.setProperty(Context.PROVIDER_URL, url);
        props.put("java.naming.ldap.factory.socket", "com.zhongan.ua.utils.LTSSSLSocketFactory");
        props.put(Context.SECURITY_PROTOCOL, "ssl");//389 端口 就去掉
        props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url");
        props.setProperty(Context.REFERRAL, "ignore");
        props.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
        props.setProperty(Context.SECURITY_PRINCIPAL, adConfig.getAD_ACCOUNT());
        props.setProperty(Context.SECURITY_CREDENTIALS, adConfig.getAD_PASSWORD());
        try {
            ctx = new InitialLdapContext(props, null);
            //ctx = new InitialDirContext(env);
        } catch (Exception err) {

        }
    }

    public static void closeContext() {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {

            }
        }
    }

    /**
     *
     * @param userName "CN=tzzy;OU=软件研发部,DC=zxf,DC=com"
     * @return
     */
    public static Boolean getUserDN(String userName) {
        if (userName == null || "".equals(userName)) {
            return false;
        }
        try {
            String searchFilter = "objectClass=user";
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String returnedAtts[] = {"memberOf"};
            searchCtls.setReturningAttributes(returnedAtts);
            NamingEnumeration answer = ctx.search(userName, searchFilter, searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
                Attributes Attrs = sr.getAttributes();
                if (Attrs != null) {
                    return true;
                }
            }
        } catch (NamingException e) {
            return false;
        }
        return false;
    }

    public static boolean addAdUser(String userName, String pwd, String description, ADConfig adConfig) {
        String userDN = "CN=" + userName + "," + adConfig.getBASEDN();
        try {
            LDAP_connect(adConfig);//链接上AD
            //if (getUserDN("CN="+userName+";OU=软件研发部,DC=zxf,DC=com")) {//如果 有这个用户了 就不在 添加了
           //     return false;
            //} else {
                BasicAttributes attrsbu = new BasicAttributes();
                BasicAttribute objclassSet = new BasicAttribute("objectclass");
                objclassSet.add("User");
                attrsbu.put(objclassSet);
                //attrsbu.put("sn", userName);
                //attrsbu.put("cn", userName);
                attrsbu.put("uid", userDN);
                //attrsbu.put("userPassword", pwd);
                attrsbu.put("description", description);
                attrsbu.put("userAccountControl", "544");
                attrsbu.put("userPrincipalName", userName + "@" + adConfig.getDN());
                attrsbu.put("pwdLastSet", "-1");
                attrsbu.put("sAMAccountName", userName);
                attrsbu.put("displayName", userName);
                ctx.createSubcontext(userDN, attrsbu);
                ModificationItem[] mods = new ModificationItem[1];
                String newQuotedPassword = "\"" + pwd + "\"";
                byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
                mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
                //修改密码
                ctx.modifyAttributes(userDN, mods);
                return true;
            //}
        } catch (Exception e) {
            System.out.println();
        } finally {
            closeContext();
        } return false;
    }

//    public static boolean delAdUser(String userName, ADConfig adConfig) {
//        String userDN = "CN=" + userName + "," + adConfig.getBASEDN();
//        try {
//            LDAP_connect(adConfig);
//            if (getUserDN("user", "CN", userName, adConfig)) {
//                ctx.destroySubcontext(userDN);
//                return true;
//            }
//        } catch (NamingException e) {
//            LOG.info("删除用户异常:", e);
//        } catch (Exception e) {
//            LOG.info("删除用户异常:", e);
//        } finally {
//            closeContext();
//        }
//        return false;
//    }
//
//    public static boolean enableUser(String userName, ADConfig adConfig) {
//        String userDN = "CN=" + userName + "," + adConfig.getBASEDN();
//        try {
//            LDAP_connect(adConfig);
//            if (getUserDN("user", "CN", userName, adConfig)) {
//                BasicAttributes attrsbu = new BasicAttributes();
//                attrsbu.remove("CN");
//                attrsbu.put("userAccountControl", "544");
//                ctx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, attrsbu);
//                return true;
//            }
//        } catch (NamingException e) {
//            System.out.println("启用用户异常");
//        } catch (Exception e) {
//            System.out.println("启用用户异常");
//        } finally {
//            closeContext();
//        }
//        return false;
//    }
//
//    public static boolean disableUser(String userName, ADConfig adConfig) {
//        String userDN = "CN=" + userName + "," + adConfig.getBASEDN();
//        try {
//            LDAP_connect(adConfig);
//            if (getUserDN("user", "CN", userName, adConfig)) {
//                BasicAttributes attrsbu = new BasicAttributes();
//                attrsbu.remove("CN");
//                attrsbu.put("userAccountControl", "514");
//                ctx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, attrsbu);
//                return true;
//            }
//        } catch (NamingException e) {
//            LOG.info("禁用用户异常:", e);
//        } catch (Exception e) {
//            LOG.info("禁用用户异常:", e);
//        } finally {
//            closeContext();
//        }
//        return false;
//    }
//
//    public static StringlistADInfo(String type, ADConfig adConfig) {
//        String result = "";
//        try {
//            LDAP_connect(adConfig);
//            String searchBase = "DC=test,DC=com";
//            String searchFilter = "objectClass=" + escapeLDAPSearchFilter(type) + "";
//            SearchControls searchCtls = new SearchControls();
//            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//            String returnedAtts[] = {"memberOf"};
//            定制返回属性 searchCtls.setReturningAttributes(returnedAtts);
//            设置返回属性集 不设置则返回所有属性 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
//            NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
//            Search for objects using the filter while (answer.hasMore()) {
//                SearchResult result1 = (SearchResult) answer.next();
//                System.err.println(result1.getName());
//                NamingEnumeration attrs = result1.getAttributes().getAll();
//                while (attrs.hasMore()) {
//                    Attribute attr = attrs.next();
//                    System.out.println(attr.getID() + " = " + attr.get());
//                }
//            }
//        } catch (NamingException e) {
//            LOG.info("获取用户列表失败", e);
//        } finally {
//            closeContext();
//        } return result;
//    }
//
//    public static String GetADInfo(String type, String filter, String name) {
//        String userName = name;
//        用户名称 if (userName == null) {
//            userName = "";
//        }
//        String company = "";
//        String result = "";
//        try {
//            域节点 String searchBase = "DC=test,DC=com";
//            LDAP搜索过滤器类 cn =*
//            name * 模糊查询 cn = name 精确查询 String searchFilter = "(objectClass=" + type + ")";
//            String searchFilter = "(&(objectClass=" + escapeLDAPSearchFilter(type) + ")(" + escapeLDAPSearchFilter(filter) + "=*" + escapeLDAPSearchFilter(name) + "*))";
//            String searchFilter = "(&(objectClass=" + type + ")(" + filter + "=*" + name + "*))";
//            创建搜索控制器
//            创建搜索控制器 SearchControls searchCtls = new SearchControls();
//            设置搜索范围
//            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//            String returnedAtts[] = {"memberOf"};
//            定制返回属性 searchCtls.setReturningAttributes(returnedAtts);
//            设置返回属性集 不设置则返回所有属性 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
//            NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
//            Search for objects using the filter 初始化搜索结果数为0 int totalResults = 0;
//            Specify the attributes to return int rows = 0;
//            while (answer.hasMoreElements()) {
//                遍历结果集 SearchResult sr = (SearchResult) answer.next();
//                得到符合搜索条件的DN++ rows;
//                String dn = sr.getName();
//                System.out.println(dn);
//                Attributes Attrs = sr.getAttributes();
//                得到符合条件的属性集 if (Attrs != null) {
//                    try {
//                        for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore(); ) {
//                            Attribute Attr = (Attribute) ne.next();
//                            得到下一个属性
//                            System.out.println(" AttributeID--" + Attr.getID().toString());
//                            result = Attr.getID().toString();
//                            读取属性值
//                            for (NamingEnumeration e = Attr.getAll(); e.hasMore(); e.next()) {
//                                company = e.next().toString();
//                                System.out.println("  AttributeValues--" + company);
//                            }
//                            System.out.println("  ---------------");
//                        }
//                    } catch (NamingException e) {
//                        LOG.info("获取属性失败", e);
//                    }
//                } if
//            } while
//            System.out.println("************************************************");
//            System.out.println("Number: " + totalResults);
//            System.out.println("counts:" + rows);
//        } catch (NamingException e) {
//            LOG.info("查询用户失败", e);
//        } return result;
//    }
//
//    public static StringescapeDN(String name) {
//        StringBuffer sb = new StringBuffer();
//        If using JDK >= 1.5 consider using StringBuilder
//        if ((name.length() > 0) && ((name.charAt(0) == ' ') || (name.charAt(0) == '#'))) {
//            sb.append('\\');
//            add the leading backslash if needed
//        } for (int i = 0; i < name.length(); i++) {
//            char curChar = name.charAt(i);
//            switch (curChar) {
//                case '\\':
//                    sb.append("\\\\");
//                    break;
//                case ',':
//                    sb.append("\\,");
//                    break;
//                case '+':
//                    sb.append("\\+");
//                    break;
//                case '"':
//                    sb.append("\\\"");
//                    break;
//                case '<':
//                    sb.append("\\<");
//                    break;
//                case '>':
//                    sb.append("\\>");
//                    break;
//                case ';':
//                    sb.append("\\;");
//                    break;
//                default:
//                    sb.append(curChar);
//            }
//        }
//        if ((name.length() > 1) && (name.charAt(name.length() - 1) == ' ')) {
//            sb.insert(sb.length() - 1, '\\');
//            add the trailing backslash if needed
//        } return sb.toString();
//    }
//
//    public static final StringescapeLDAPSearchFilter(String filter) {
//        StringBuffer sb = new StringBuffer();
//        If using JDK >= 1.5 consider using StringBuilder for (int i = 0; i < filter.length(); i++) {
//            char curChar = filter.charAt(i);
//            switch (curChar) {
//                case '\\':
//                    sb.append("\\5c");
//                    break;
//                case '*':
//                    sb.append("\\2a");
//                    break;
//                case '(':
//                    sb.append("\\28");
//                    break;
//                case ')':
//                    sb.append("\\29");
//                    break;
//                case '\u0000':
//                    sb.append("\\00");
//                    break;
//                default:
//                    sb.append(curChar);
//            }
//        }
//        return sb.toString();
//    }
//
//    public static ListGetADInfo(String type, String filter, String name, ADConfig adConfig) {
//        LDAP_connect(adConfig);
//        List userlist = new ArrayList();
//        String userName = name;
//        用户名称 if (userName == null) {
//            userName = "";
//        }
//        String company = "";
//        String result = "";
//        try {
//            域节点 String searchBase = "CN=Users,DC=test,DC=com";
//            LDAP搜索过滤器类 cn =*name * 模糊查询
//            cn = name 精确查询 String searchFilter = "(objectClass=" + type + ")";
//            String searchFilter = "(&(objectClass=" + type + "))";
//            创建搜索控制器
//            SearchControls searchCtls = new SearchControls();
//            设置搜索范围
//            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//            String returnedAtts[] = {"objectCategory"};
//            定制返回属性 searchCtls.setReturningAttributes(returnedAtts);
//            设置返回属性集 不设置则返回所有属性 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
//            NamingEnumeration answer = ctx.search(adConfig.getBASEDN(), searchFilter, searchCtls);
//            Search for objects using the filter 初始化搜索结果数为0 int totalResults = 0;
//            Specify the attributes to return int rows = 0;
//            while (answer.hasMoreElements()) {
//                遍历结果集 SearchResult sr = (SearchResult) answer.next();
//                得到符合搜索条件的DN++ rows;
//                String dn = sr.getName();
//                System.out.println(dn);
//                String subdn = StringUtils.substringAfter(dn, "CN=");
//                userlist.add(subdn);
//                Attributes Attrs = sr.getAttributes();
//                得到符合条件的属性集 if (Attrs != null) {
//                    try {
//                        for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore(); ) {
//                            Attribute Attr = (Attribute) ne.next();
//                            得到下一个属性
//                            System.out.println(" AttributeID=属性名：" + Attr.getID().toString());
//                            读取属性值
//                            for (NamingEnumeration e = Attr.getAll(); e.hasMore(); totalResults++) {
//                                company = e.next().toString();
//                                System.out.println("AttributeValues=属性值：" + company);
//                            }
//                            System.out.println("  ---------------");
//                        }
//                    } catch (NamingException e) {
//                        LOG.info("查询ad用户异常", e);
//                        System.err.println("Throw Exception : " + e);
//                    }
//                } if
//            } whileSystem.out.println("************************************************");
//            System.out.println("Number: " + totalResults);      /
//            System.out.println("总共用户数：" + rows);
//        } catch (NamingException e) {
//            LOG.info("查询ad用户失败", e);
//        } closeContext();
//        return userlist;
//    }
//
//    public static ListqueryExistADUser(String type, String filter, String name, ADConfig adConfig) {
//        LDAP_connect(adConfig);
//        List userlist = new ArrayList();
//        String userName = name;
//        用户名称 if (userName == null) {
//            userName = "";
//        }
//        String company = "";
//        String result = "";
//        try {
//            域节点 String searchBase = "CN=Users,DC=test,DC=com";
//            LDAP搜索过滤器类 cn =*name * 模糊查询
//            cn = name 精确查询 String searchFilter = "(&(objectClass=" + type + ")(" + filter + "=" + name + "))";
//            创建搜索控制器 SearchControls searchCtls = new SearchControls();
//            设置搜索范围
//            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//            String returnedAtts[] = {"objectCategory"};
//            定制返回属性 searchCtls.setReturningAttributes(returnedAtts);
//            设置返回属性集 不设置则返回所有属性 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
//            NamingEnumeration answer = ctx.search(adConfig.getBASEDN(), searchFilter, searchCtls);
//            Search for
//            objects using the filter System.out.println("answer" + answer);
//            初始化搜索结果数为0
//            int totalResults = 0;
//            Specify the attributes to return int rows = 0;
//            while (answer.hasMoreElements()) {
//                遍历结果集 SearchResult sr = (SearchResult) answer.next();
//                得到符合搜索条件的DN++ rows;
//                String dn = sr.getName();
//                System.out.println(dn);
//                String subdn = StringUtils.substringAfter(dn, "CN=");
//                userlist.add(subdn);
//            } while
//        } catch (NamingException e) {
//            LOG.info("查询ad用户失败", e);
//        } closeContext();
//        return userlist;
//    }
//
//    public static void main(String[] args) {
//        ADConfig ac = new ADConfig();
//        ac.setBASEDN("CN=Users,DC=test,DC=com");
//        ac.setDN("test.com");
//        ac.setAD_SERVER_PORT("636");
//        ac.setAD_ACCOUNT("管理员账户名（能有管理普通账户的账号）");
//        ac.setAD_SERVER("你的域控制器 的 ip （1.1.1.1）或者计算机名称地址（aaa.test.com ,aaa为计算机名称，test.com为地址，采用计算机名称地址访问最好 ping 一下，在不在一个网段中，能被解析出来）");
//        ac.setAD_PASSWORD("管理员密码");
//        LDAP_connect(ac);
//        LDAP_connect(ac);
//        addAdUser("ceshihehe", "Abcd123456", "aa", ac);
//        System.out.println(CollectionUtils.isEmpty(queryExistADUser("user", "cn", "xidada", ac)));
//        closeContext();
//    }
//}
//    免证书的类 来了import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import java.security.SecureRandom;import javax.net.SocketFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;
//
//public class LTSSSLSocketFactoryextends SSLSocketFactory {
//    private SSLSocketFactorysocketFactory;
//
//    public LTSSSLSocketFactory() {
//        try {
//            SSLContext ctx = SSLContext.getInstance("TLS");
//            ctx.init(null, new TrustManager[]{new LTSTrustmanager()}, new SecureRandom());
//            socketFactory = ctx.getSocketFactory();
//        } catch (Exception ex) {
//            ex.printStackTrace(System.err);
//        }
//    }
//
//    public static SocketFactorygetDefault() {
//        return new LTSSSLSocketFactory();
//    }
//
//    @Override
//
//    public SocketcreateSocket(Socket arg0, String arg1, int arg2, boolean arg3) throws IOException {
//        return null;
//    }
//
//    @Override

//    public String[] getDefaultCipherSuites() {
//        return socketFactory.getDefaultCipherSuites();
//    }
//
//    @Override
//
//    public String[] getSupportedCipherSuites() {
//        return socketFactory.getSupportedCipherSuites();
//    }
//
//    @Override
//
//    public SocketcreateSocket(String arg0, int arg1) throws IOException, UnknownHostException {
//        return socketFactory.createSocket(arg0, arg1);
//    }
//
//    @Override
//
//    public SocketcreateSocket(InetAddress arg0, int arg1) throws IOException {
//        return socketFactory.createSocket(arg0, arg1);
//    }
//
//    @Override
//
//    public SocketcreateSocket(String arg0, int arg1, InetAddress arg2, int arg3) throws IOException, UnknownHostException {
//        return socketFactory.createSocket(arg0, arg1, arg2, arg3);
//    }
//
//    @Override
//
//    public SocketcreateSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
//        return socketFactory.createSocket(arg0, arg1, arg2, arg3);
//    }
//}另一个类:import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;
//
//public class LTSTrustmanagerimplements X509TrustManager {
//    @Override
//
//    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
//    }
//
//    @Override
//
//    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
//    }
//
//    @Override
//
//    public X509Certificate[] getAcceptedIssuers() {
//        return new java.security.cert.X509Certificate[0];
//    }
}

